import { PUT, TAKE, FORK } from "./effectTypes";

function runSaga(env, saga) {
  let { channel, dispatch } = env;
  let it = typeof saga[Symbol.iterator] === "function" ? saga : saga();
  function next(val) {
    let { value: effect, done } = it.next(val);
    if (!done) {
      if (typeof effect[Symbol.iterator] === "function") {
        runSaga(env, effect);
      } else {
        // 根据不同的effect进行不同的处理
        // next(effect)
        switch (effect.type) {
          case TAKE:
            // effect={type: 'TAKE', actionTypes: 'ASYNC_ADD'}
            channel.on(effect.actionType, next);
            break;
          case PUT:
            dispatch(effect.action);
            break;
          case FORK:
            runSaga(env, effect.saga);
            next();
            break;
          default:
            break;
        }
      }
    }
  }
  next();
}
export default runSaga;
